<template>
  <div class="user-page">
    <van-nav-bar 
      title="个人中心" 
      fixed
      placeholder
      :border="false"
      :safe-area-inset-top="true"
    />
    <!-- 头部用户信息 -->
    <div class="user-header">
      <img class="avatar" :src="userAvatar" @click="goUserOrLogin" />
      <div class="user-info" @click="goUserOrLogin" style="cursor:pointer;">
        <div class="username">{{ userName }}</div>
        <div class="vip" v-if="isLogin">金卡会员</div>
      </div>
    </div>
    <!-- 数据卡片 -->
    <div class="user-stats">
      <div class="stat-item">
        <img src="/src/assets/images/rice.png" width="22px">
        <div class="stat-value">{{ nutritionData.calories }}大卡</div>
        <div class="stat-label">摄入总量</div>
      </div>
      <div class="stat-item">
        <img src="/src/assets/images/danbaizhi.png" width="22px">
        <div class="stat-value">{{ nutritionData.protein }}克</div>
        <div class="stat-label">蛋白质</div>
      </div>
      <div class="stat-item">
        <img src="/src/assets/images/sheru.png" width="22px">
        <div class="stat-value">{{ nutritionData.carbs }}克</div>
        <div class="stat-label">碳水</div>
      </div>
    </div>
    <!-- 设置列表 -->
    <div class="settings-section">
      <van-cell-group title="设置">
        <van-cell
          title="个人信息"
          icon="user-o"
          is-link
          @click="goPage('user-profile')"
        />
        <van-cell
          title="通知设置"
          icon="bell"
          is-link
          @click="goPage('tongzhi')"
        />
        <van-cell
          title="我的收藏"
          icon="star-o"
          is-link
          @click="goPage('user-favorite')"
        />
        <van-cell
          title="语言设置"
          icon="underway-o"
          is-link
          value="简体中文"
          @click="showLanguageToast"
        />
      </van-cell-group>
      <van-cell-group title="安全与隐私">
        <van-cell
          title="密码管理"
          icon="lock"
          is-link
          @click="goPage('user-password')"
        />
        <van-cell
          title="清除缓存"
          icon="delete-o"
          is-link
          @click="showClearCache"
        />
      </van-cell-group>
      <van-cell-group title="帮助与反馈">
        <van-cell
          title="意见反馈"
          icon="comment-o"
          is-link
          @click="goPage('feedback')"
        />
        <van-cell
          title="关于我们"
          icon="info-o"
          is-link
          @click="goPage('about')"
        />
      </van-cell-group>
    </div>
    <div class="logout-btn-wrap">
      <van-button class="logout-btn" block type="danger" @click="logout">退出登录</van-button>
    </div>

    <!-- 清除缓存弹窗 -->
    <van-dialog
      v-model:show="showClearCacheDialog"
      title="清除缓存"
      show-cancel-button
      @confirm="handleClearCache"
    >
      <div class="dialog-content">
        确定要清除所有缓存数据吗？
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, onMounted, onUnmounted } from 'vue'
import { showToast } from 'vant'
import { db, STORES } from '../utils/db'
import { getWeeklyNutrition } from '../utils/nutritionSync'

const router = useRouter()
const DEFAULT_AVATAR = 'https://img.yzcdn.cn/vant/cat.jpeg'
const userName = ref('请登录')
const userAvatar = ref(DEFAULT_AVATAR)
const isLogin = ref(false)

// 添加响应式数据
const nutritionData = ref({
  calories: 0,
  protein: 0,
  carbs: 0,
  fat: 0
})

const goUserOrLogin = () => {
  if (isLogin.value) {
    router.push('/user/profile')
  } else {
    router.push('/login')
  }
}

// 加载营养数据
const loadNutritionData = async () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  try {
    const { weekTotal } = await getWeeklyNutrition(userEmail)
    
    // 更新数据卡片
    nutritionData.value = {
      calories: Math.round(weekTotal.calories),
      protein: Math.round(weekTotal.protein),
      carbs: Math.round(weekTotal.carbs)
    }
  } catch (error) {
    console.error('加载营养数据失败:', error)
    showToast('加载数据失败')
  }
}

// 监听数据库变化
const setupDBListener = () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  // 每30秒刷新一次数据
  const timer = setInterval(loadNutritionData, 30000)
  return timer
}

onMounted(() => {
  // 检查登录状态
  isLogin.value = !!localStorage.getItem('isLogin')
  if (isLogin.value) {
      const userEmail = localStorage.getItem('userEmail')
      if (userEmail) {
      db.get(STORES.USER_LIST, userEmail).then(user => {
        if (user) {
          userName.value = user.username || '测试用户'
          userAvatar.value = user.avatar || DEFAULT_AVATAR
        }
      }).catch(error => {
      console.error('获取用户信息失败:', error)
      showToast('获取用户信息失败')
      })
    }
  }

  loadNutritionData()
  const nutritionTimer = setupDBListener()

onUnmounted(() => {
  if (nutritionTimer) {
    clearInterval(nutritionTimer)
  }
  })
})

const goPage = async (path) => {
  if (!isLogin.value) {
    showToast('请先登录')
    router.push('/login')
    return
  }

  try {
    switch (path) {
      case 'user-profile':
        await router.push('/user/profile')
        break
      case 'user-password':
        await router.push('/user/password')
        break
      case 'user-favorite':
        await router.push('/user/favorite')
        break
      case 'tongzhi':
        await router.push('/tongzhi')
        break
      case 'feedback':
        await router.push('/feedback')
        break
      case 'about':
        await router.push('/about')
        break
      default:
        await router.push(path)
    }
  } catch (error) {
    console.error('页面跳转失败:', error)
    showToast('页面跳转失败')
  }
}

const logout = () => {
  localStorage.removeItem('isLogin')
  localStorage.removeItem('userName')
  localStorage.removeItem('userEmail')
  localStorage.removeItem('userPwd')
  localStorage.removeItem('userAvatar')
  router.replace('/search')
}

const showLanguageToast = () => {
  showToast({
    message: '膳小搭暂时只支持中文，更多语言敬请期待~',
    position: 'middle',
    duration: 2000
  })
}

// 清除缓存相关
const showClearCacheDialog = ref(false)
const showClearCache = () => {
  showClearCacheDialog.value = true
}

const handleClearCache = () => {
  showToast('缓存清除成功')
  window.location.reload()
}
</script>

<style scoped>
.user-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e9eafc 0%, #e6e6fa 100%);
  padding-bottom: 24px;
}

.van-nav-bar {
  background: #fff !important;
}

.van-nav-bar :deep(.van-nav-bar__title) {
  color: #333;
  font-size: 17px;
  font-weight: 600;
}

.user-header {
  display: flex;
  align-items: center;
  padding: 20px 16px;
  background: #fff;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 12px;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.user-info {
  flex: 1;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
}

.vip {
  font-size: 12px;
  color: #d9cb1d;
  background: rgba(217, 203, 29, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  background: #fff;
  border-radius: 16px;
  margin: 0 16px 12px 16px;
  padding: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  position: relative;
}

.stat-item:not(:last-child)::after {
  content: '';
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 1px;
  height: 24px;
  background: #f0f0f0;
}

.stat-value {
  font-size: 16px;
  font-weight: 600;
  color: #4caf50;
  margin: 6px 0 2px 0;
}

.stat-label {
  font-size: 12px;
  color: #888;
}

.settings-section {
  margin: 0 16px;
}

.van-cell-group {
  margin-bottom: 12px;
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.van-cell-group :deep(.van-cell-group__title) {
  padding: 16px 16px 8px;
  font-size: 14px;
  color: #666;
}

.van-cell {
  font-size: 15px;
  color: #333;
  padding: 12px 16px;
}

.van-cell :deep(.van-icon) {
  color: #7c5dfa;
  font-size: 18px;
  margin-right: 8px;
}

.logout-btn-wrap {
  margin: 24px 16px 0;
}

.logout-btn {
  height: 44px;
  border-radius: 22px;
  font-size: 16px;
  font-weight: 600;
  background: #ff4d4f;
  border: none;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.2);
}

.logout-btn:active {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(255, 77, 79, 0.15);
}

.dialog-content {
  padding: 20px;
  text-align: center;
}
</style>